<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
	{
	style: {
	navigationBarTitleText: '个人信息',
	enablePullDownRefresh: false,
	},
	}
</route>
<template>
	<view class="page">
		<view class="p-4">
			<wd-cell-group border custom-class="rounded-lg overflow-hidden px-4">
				<wd-cell center title="头像" value="内容" required>
					<view class="relative">
						<wd-img width="60" height="60" radius="50%" :src="formatUrl(userInfo.avatar)"></wd-img>
						<button :disabled="!isEdit" open-type="chooseAvatar" class="hide-button"
							@chooseavatar="handleChooseAvatar"></button>
					</view>
				</wd-cell>
				<wd-cell center title="昵称" required>
					<wd-input v-model="userInfo.nickname" :readonly="!isEdit" :no-border="true" type="nickname"
						custom-input-class="text-right" placeholder="请输入昵称" @blur="handleUpdateName" />
				</wd-cell>
			</wd-cell-group>

			<wd-cell-group border custom-class="rounded-lg overflow-hidden px-4 mt-4">
				<wd-cell center title="城市" required>
					<wd-input :readonly="!isEdit" :no-border="true" v-model="userInfo.city"
						custom-input-class="text-right" placeholder="请输入城市" />
				</wd-cell>
				<wd-cell center title="行业" required>
					<wd-input :readonly="!isEdit" :no-border="true" v-model="userInfo.industry"
						custom-input-class="text-right" placeholder="请输入行业" />
				</wd-cell>
				<wd-cell center title="职业" required>
					<wd-input :readonly="!isEdit" :no-border="true" v-model="userInfo.jobs"
						custom-input-class="text-right" placeholder="请输入职业" />
				</wd-cell>
				<wd-cell center title="兴趣点" title-width="150rpx" required>
					<view class="flex items-center justify-end" @click="handleOpenPopup">
						<view class="mr-1">
							<view v-for="(item, index) in interest" :key="index">{{ item }}</view>
						</view>
						<wd-icon name="arrow-right" color="#999" size="28rpx"></wd-icon>
					</view>
				</wd-cell>
			</wd-cell-group>

			<view class="w-4/5 mx-auto mt-4">
				<wd-button v-if="isEdit" :loading="loading" :round="false" :block="true" custom-class="w-full"
					@click="handleSave">
					保存
				</wd-button>
				<wd-button v-else type="info" plain :round="false" :block="true" custom-class="w-full"
					@click="toggleEditStatus">
					编辑信息
				</wd-button>
			</view>
		</view>

		<wd-popup v-model="show" position="bottom" :safe-area-inset-bottom="true" custom-style="border-radius:32rpx;">
			<interests v-model="userInfo.interest" @close="close" />
		</wd-popup>
	</view>
</template>

<script setup>
	import {
		fetchUpdateUserInfo,
		fetchUpdateProfile
	} from '@/service/user'
	import useUserStore from '@/store/user'
	import {
		showToast,
		uploadFile,
		showLoading
	} from '@/utils/uni'
	import usePopup from '@/hooks/usePopup'
	import {
		formatUrl
	} from '@/utils/format'
	import {
		deepClone
	} from '@/utils/index'
	import interests from './components/interests.vue'
	import user from '@/store/user'

	const isEdit = ref(true)
	const {
		show,
		open,
		close
	} = usePopup()

	const loading = ref(false)
	const userStore = useUserStore()

	const userInfo = ref(deepClone(userStore.userInfo))
	const interest = computed(() => {
		const v = userInfo.value.interest
		if (!v) return []
		return v.split(',')
	})

	const header = computed(() => {
		return {
			token: userStore.token,
			version: import.meta.env.VITE_VERSION,
		}
	})

	function toggleEditStatus() {
		isEdit.value = !isEdit.value
	}

	function handleOpenPopup() {
		if (isEdit.value) open()
	}

	async function updateInfo(field, value) {
		await fetchUpdateUserInfo({
			field,
			value,
		})
	}

	function filterNullAttrs(obj) {
		const newObj = {}
		Object.keys(obj).forEach((key) => {
			if (obj[key]) {
				newObj[key] = obj[key]
			}
		})

		return newObj
	}

	async function handleSave() {
		try {
			loading.value = true
			const {
				avatar,
				nickname,
				city,
				jobs,
				industry,
				interest
			} = userInfo.value

			await fetchUpdateProfile(
				filterNullAttrs({
					city,
					jobs,
					industry,
					interest,
				}),
			)

			await updateInfo('avatar', avatar)
			await updateInfo('nickname', nickname)
			showToast('更新成功')
			// toggleEditStatus()
		} catch (err) {
			console.log(err)
			// uni.hideLoading()
			showToast(err.data.msg || '保存失败,请填写相应信息后重试')
		} finally {
			loading.value = false
		}
	}

	function handleUpdateName({
		value
	}) {
		userInfo.value.nickname = value
	}

	async function handleChooseAvatar(e) {

		try {
			showLoading('上传头像中')
			const uploadRes = await uploadFile(e.detail.avatarUrl, {
				header: header.value,
			})
			const {
				uri
			} = uploadRes.data
			userInfo.value.avatar = uri

		} catch (err) {
			console.log(err)

			showToast('更新失败，请重试')
		} finally {
			uni.hideLoading()
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		@apply bg-[#f4f4f4];
		min-height: 100vh;
		--wot-color-white: white;
	}
</style>